/*
 * $RCSfile: UserAction.java,v $
 * $Revision: 1.1 $
 * $Date: 2017-05-17 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.webcat.action.oracle;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.skin.j2ee.action.BaseAction;
import com.skin.j2ee.annotation.UrlPattern;
import com.skin.j2ee.util.Ajax;
import com.skin.util.StringUtil;
import com.skin.webcat.database.oracle.Oracle;
import com.skin.webcat.database.oracle.OracleURL;
import com.skin.webcat.database.oracle.ServerPermission;
import com.skin.webcat.util.Jdbc;
import com.skin.webcat.util.Webcat;

/**
 * <p>Title: UserAction</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class UserAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(UserAction.class);

    /**
     * @throws ServletException
     * @throws IOException
     */
    @UrlPattern("/webcat/oracle/user.html")
    public void tablespace() throws ServletException, IOException {
        String name = this.getTrimString("name");
        OracleURL oracleURL = null;

        if(name.length() > 0) {
            Connection connection = null;

            try {
                connection = Webcat.getConnection(name);
                oracleURL = Oracle.getURL(connection);
            }
            catch(Exception e) {
                logger.error(e.getMessage(), e);
            }
            finally {
                Jdbc.close(connection);
            }
        }

        /**
         * 使用示例URL
         */
        if(oracleURL == null) {
            oracleURL = OracleURL.parse("jdbc:oracle:thin:@192.168.1.1:1521:ORCL");
        }

        this.setAttribute("name", name);
        this.setAttribute("oracleURL", oracleURL);
        this.forward("/template/webcat/oracle/user.jsp");
    }

    /**
     * @throws ServletException
     * @throws IOException
     */
    @UrlPattern("/webcat/oracle/user/getCreateSql.html")
    public void getCreateSql() throws ServletException, IOException {
        String sql = this.getCreateUserSql();
        Ajax.success(this.request, this.response, sql);
    }

    /**
     * @throws ServletException
     * @throws IOException
     */
    @UrlPattern("/webcat/oracle/user/create.html")
    public void create() throws ServletException, IOException {
        String sql = this.getCreateUserSql();
        Ajax.success(this.request, this.response, sql);
    }

    /**
     * @return String
     */
    private String getCreateUserSql() {
        String userName = this.getTrimString("userName");
        String password = this.getTrimString("password");
        StringBuilder buffer = new StringBuilder();
        buffer.append("-- drop user\r\n");
        buffer.append("drop user ${userName} cascade;\r\n");
        buffer.append("\r\n");
        buffer.append("-- create user\r\n");
        buffer.append("create user ${userName} identified by ${password}\r\n");
        buffer.append("default tablespace ${tablespaceName}\r\n");
        buffer.append("temporary tablespace ${tablespaceName};\r\n");
        buffer.append("\r\n");

        /**
         * 服务器权限
         */
        List<ServerPermission> serverPermissionList = this.getServerPermissionList();

        if(serverPermissionList != null && serverPermissionList.size() > 0) {
            buffer.append("-- grant\r\n");

            for(ServerPermission serverPermission : serverPermissionList) {
                buffer.append("grant ");
                buffer.append(serverPermission.getName());
                buffer.append(" to ${userName}");

                if(serverPermission.getAdmin()) {
                    buffer.append(" with admin option");
                }
                buffer.append(";\r\n");
            }
        }
        buffer.append("\r\n\r\n\r\n\r\n");

        Map<String, String> context = new HashMap<String, String>();
        context.put("userName", userName);
        context.put("password", password);
        return StringUtil.replace(buffer.toString(), context);
    }

    /**
     * @return List<ServerPermission>
     */
    private List<ServerPermission> getServerPermissionList() {
        String[] array = this.getParameterValues("serverPermission");
        List<ServerPermission> serverPermissionList = new ArrayList<ServerPermission>();

        if(array == null || array.length < 1) {
            return serverPermissionList;
        }

        for(String name : array) {
            ServerPermission serverPermission = new ServerPermission();

            if(name.endsWith(" with admin")) {
                name = name.substring(0, name.length() - 11);
                serverPermission.setName(name);
                serverPermission.setAdmin(true);
            }
            else {
                serverPermission.setName(name);
                serverPermission.setAdmin(false);
            }
            serverPermissionList.add(serverPermission);
        }
        return serverPermissionList;
    }
}
